package com.wave.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wave.common.core.domain.PageQuery;
import com.wave.common.core.page.TableDataInfo;
import com.wave.common.exception.ServiceException;
import com.wave.common.utils.StringUtils;
import com.wave.system.domain.SysToolBoardTask;
import com.wave.system.domain.SysToolShelfTask;
import com.wave.system.domain.bo.SysToolShelfTaskBo;
import com.wave.system.domain.vo.SysToolShelfTaskVo;
import com.wave.system.mapper.SysToolShelfTaskMapper;
import com.wave.system.service.ISysProduceArrangeService;
import com.wave.system.service.ISysToolShelfTaskService;
import com.wave.system.util.Modbus4jUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 工装架任务Service业务层处理
 *
 * @author wave
 * @date 2024-10-12
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class SysToolShelfTaskServiceImpl implements ISysToolShelfTaskService {

    private final SysToolShelfTaskMapper baseMapper;

    private final ISysProduceArrangeService produceArrangeService;

    /**
     * 查询工装架任务
     */
    @Override
    public SysToolShelfTaskVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询工装架任务列表
     */
    @Override
    public TableDataInfo<SysToolShelfTaskVo> queryPageList(SysToolShelfTaskBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysToolShelfTask> lqw = buildQueryWrapper(bo);
        Page<SysToolShelfTaskVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询工装架任务列表
     */
    @Override
    public List<SysToolShelfTaskVo> queryList(SysToolShelfTaskBo bo) {
        LambdaQueryWrapper<SysToolShelfTask> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysToolShelfTask> buildQueryWrapper(SysToolShelfTaskBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysToolShelfTask> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getShelfNumber()), SysToolShelfTask::getShelfNumber, bo.getShelfNumber());
        lqw.like(StringUtils.isNotBlank(bo.getProductNumber()), SysToolShelfTask::getProductNumber, bo.getProductNumber());
        lqw.like(StringUtils.isNotBlank(bo.getTargetExport()), SysToolShelfTask::getTargetExport, bo.getTargetExport());
        lqw.ne(SysToolShelfTask::getTaskStatus, "放行完成");
        lqw.like(StringUtils.isNotBlank(bo.getTaskStatus()), SysToolShelfTask::getTaskStatus, bo.getTaskStatus());
        lqw.gt(params.get("beginTime") != null, SysToolShelfTask::getCreateTime, params.get("beginTime"));
        lqw.lt(params.get("endTime")!=null, SysToolShelfTask::getCreateTime, params.get("endTime"));
        lqw.orderByAsc(SysToolShelfTask::getPackageLine);
        return lqw;
    }

    /**
     * 新增工装架任务
     */
    @Override
    public Boolean insertByBo(SysToolShelfTaskBo bo) {
        SysToolShelfTask add = BeanUtil.toBean(bo, SysToolShelfTask.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    private void validEntityBeforeSave(SysToolShelfTask add) {

    }

    /**
     * 修改工装架任务
     */
    @Override
    public Boolean updateByBo(SysToolShelfTaskBo bo) {
        SysToolShelfTask update = BeanUtil.toBean(bo, SysToolShelfTask.class);
        SysToolShelfTask sysToolShelfTask = baseMapper.selectById(bo.getId());
        if (ObjectUtil.isEmpty(sysToolShelfTask)) {
            return true;
        }
        Integer packageLine = sysToolShelfTask.getPackageLine();
        if ("放行完成".equals(update.getTaskStatus()) && packageLine != null) {
            log.info("工装架:{}收到手动完成指令", sysToolShelfTask.getShelfNumber());
            validEntityBeforeUpdate(sysToolShelfTask);
            boolean success = true;
            switch (packageLine) {
                case 1:
                    success = Modbus4jUtils.writeCoil(1, 4168, true);
                    break;
                case 2:
                    success = Modbus4jUtils.writeCoil(1, 4169, true);
                    break;
                case 3:
                    success = Modbus4jUtils.writeCoil(1, 4170, true);
                    break;
                case 4:
                    success = Modbus4jUtils.writeCoil(1, 4171, true);
                    break;
                default:
                    break;
            }
            if (!success) {
                throw new ServiceException("手动结束工装架任务通知PLC失败");
            }
            produceArrangeService.pushMesCheck(packageLine, 1);
            return baseMapper.updateById(update) > 0;
        }
        return false;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeUpdate(SysToolShelfTask entity) {
        Integer packageLine = entity.getPackageLine();
        Boolean autoRun = Modbus4jUtils.readCoilStatus(1, 4968);
        if (!autoRun) {
            throw new ServiceException("PLC程序不处于自动运行中,请稍后再试!");
        }
        boolean[] booleans;
        if (packageLine == 1 || packageLine == 2) {
            booleans = Modbus4jUtils.batchReadCoilStatus(1, 4937, 2);
        } else {
            booleans = Modbus4jUtils.batchReadCoilStatus(1, 4929, 2);
        }
        boolean b = booleans[0];
        boolean b1 = booleans[1];
        if (b || b1) {
            throw new ServiceException("机器人取料中或者下料中,请稍后再试!");
        }
    }

    /**
     * 批量删除工装架任务
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
